package com.peng.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @auther zzyy
 * @create 2025-03-12 23:24
 */
@Service
public class WeatherService {
    //和风天气开发服务 https://dev.qweather.com/
    private static final String API_KEY = "a37a94a3f3b24ccfac10045eb7da7959"; // 替换成你自己的和风天气API密钥
    // 和风天气API的URL模板，
    // location = %s就是城市编号 如北京：101010100
    // KEY = %s就是API_KEY
    private static final String BASE_URL = "https://devapi.qweather.com/v7/weather/now?location=%s&key=%s";

    public JsonNode getWeatherV2(String city) throws Exception {
        String url = String.format(BASE_URL, city, API_KEY);
        // 使用默认配置创建HttpClient实例
        var httpClient = HttpClients.createDefault();

        // 创建请求工厂并将其设置给RestTemplate
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        String response = new RestTemplate(factory).getForObject(url, String.class);

        // 解析JSON响应
        JsonNode jsonNode = new ObjectMapper().readTree(response);
        return jsonNode;
    }
}
